<template>
  <el-form ref="ruleForm"
           v-loading="boxLoading"
           element-loading-text="拼命加载中"
           element-loading-spinner="el-icon-loading"
           class="form-style"
           :model="ruleForm"
           label-width="90px">
    <number-type v-if="!boxLoading"
                 :form-info="ruleForm"
                 :transport-type="transportType" />
    <div v-if="!boxLoading"
         class="footer-button">
      <el-button type="default"
                 @click="handleCancel">取消</el-button>
      <el-button type="primary"
                 :loading="loading"
                 @click="handleSubmit('ruleForm')">{{
          loading ? "提交中 ..." : "确 定"
        }}</el-button>
    </div>
  </el-form>
</template>

<script>
import numberType from "@components/numberType/index";
import { order } from "@/api/index.js";
import axios from 'axios';

export default {
  name: "WaybillDeviceBind",
  components: {
    numberType
  },
  inheritAttrs: true,
  props: {
    value: Object,
    query: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      loading: false,
      boxLoading: true,
      formData: {},
      params: {},
      ruleForm: {
        trackType: 1,
        deviceCode: "", //电子回单号/快递单号
        secondDeviceCode: "", //第二段 车次/航班号/电子回单号
        thirdDeviceCode: "", //第三段电子回单
        isThirdShow: true, //第三段显示
        deleteFlag: false,
        checkValue: null, //多式联运
        currentAddress: [], //多式联运路径
        flyNo: null,
        flyTime: null,
        trainNum: null,
        trainTime: null,
        trainForm: null,
        trainTo: null,
        receiptAddress: {
          //火车/飞机/电子回单第三段 电子回单途径地区
          wayCity: "",
          wayCityCode: "",
          wayDistrict: "",
          wayDistrictCode: "",
          wayProvince: "",
          wayProvinceCode: "",
          wayAddress: ""
        },
        secordReceiptAddress: {
          //电子回单第二段 电子回单途径地区
          wayCity: "",
          wayCityCode: "",
          wayDistrict: "",
          wayDistrictCode: "",
          wayProvince: "",
          wayProvinceCode: "",
          wayAddress: ""
        },
        fromAddress: {
          city: ""
        },
        toAddress: {
          city: ""
        },
        toTime: null,
        fromTime: null,
        transportType: null
      }
    }
  },
  computed: {
    transportType () {
      return this.query?.transportType
    },
    deviceCode () {
      return this.value.deviceCode
    },
    waybillIds () {
      return this.query.waybillIds || [];
    },
    orderIds () {
      return this.query.orderIds || [];
    }
  },
  watch: {
    value: {
      handler (value) {
        this.boxLoading = true
        this.$nextTick(() => {
          // transportType等于onebill、batchWaybill时，不需要查询接口
          if (['batchWaybill', 'onebill'].includes(this.transportType)) {
            if (this.transportType === 'batchWaybill') {
              this.ruleForm.deviceCode = null;
            }
            if (value.trackType === 3) {
              this.ruleForm.trackType = 1;
            } else {
              this.ruleForm.trackType = value.trackType || 1;
            }
            this.ruleForm.deviceCode = this.ruleForm.trackType === 1 ? (value.deviceCode ? value.deviceCode.substring(8, value.deviceCode.length) : null) : value.deviceCode;
            this.boxLoading = false
          } else {
            this.getInfo(value)
          }
        })
      },
      immediate: true
    }
  },
  methods: {
    async getInfo (value) {
      this.ruleForm.fromAddress.city = value.fromCity;
      this.ruleForm.toAddress.city = value.toCity;
      this.ruleForm.fromTime = value.fromTime;
      this.ruleForm.toTime = value.toTime;
      if (value.trackType === 3) {
        this.ruleForm.trackType = 1;
      } else {
        this.ruleForm.trackType = value.trackType || 1;
      }
      this.ruleForm.deviceCode = this.ruleForm.trackType === 1 ? (value.deviceCode ? value.deviceCode.substring(8, value.deviceCode.length) : null) : value.deviceCode;
      this.ruleForm.waybillId = value.waybillId || value.id;
      this.ruleForm.combineId = value.combineId || null;

      let { data } = await order.orderDetailsApi(value.orderId);
      const transports = data?.track?.routes;
      if (transports && transports.length) {
        this.ruleForm.checkValue = transports[0].type === 4 ? 3 : transports[0].type;
        if ([1, 2].includes(this.ruleForm.checkValue)) {
          this.ruleForm.currentAddress = [
            { stationName: transports[0].route.startPlace },
            { stationName: transports[0].route.endPlace }
          ];
          this.ruleForm.secondDeviceCode = transports[0].route.transitNo;
          if (this.ruleForm.checkValue == 1) {
            this.ruleForm.flyNo = transports[0].route.transitNo;
            this.ruleForm.flyTime = transports[0].route.startTime;
          } else if (this.ruleForm.checkValue == 2) {
            this.ruleForm.trainNum = transports[0].route.transitNo;
            this.ruleForm.trainTime = transports[0].route.startTime;
            this.ruleForm.trainForm = transports[0].route.startPlace;
            this.ruleForm.trainTo = transports[0].route.endPlace;
          }
          this.ruleForm.isThirdShow = false;
          this.ruleForm.deleteFlag = true;
          if (transports.length > 1) {
            this.ruleForm.isThirdShow = true;
            this.ruleForm.deleteFlag = false;
            this.ruleForm.thirdDeviceCode =
              transports[1].route.deviceCode.substring(
                8,
                transports[1].route.deviceCode.length
              );
            this.ruleForm.receiptAddress = { ...transports[1].route };
          }
          this.boxLoading = false
        } else {
          let arr = [];
          transports.map((item, index) => {
            let itemData = item.route;
            arr.push({ stationName: itemData.wayCity });
            if (index === 0) {
              this.ruleForm.secondDeviceCode = itemData.deviceCode.substring(
                8,
                itemData.deviceCode.length
              );
              this.ruleForm.secordReceiptAddress = { ...itemData };
              this.ruleForm.isThirdShow = false;
            } else {
              this.ruleForm.isThirdShow = true;
              this.ruleForm.thirdDeviceCode = itemData.deviceCode.substring(
                8,
                itemData.deviceCode.length
              );
              this.ruleForm.receiptAddress = { ...itemData };
            }
          });
          this.ruleForm.currentAddress = [...arr];
          this.boxLoading = false
        }
      } else {
        this.ruleForm.checkValue = null;
        this.ruleForm.currentAddress = [];
        for (let key in this.ruleForm.receiptAddress) {
          this.ruleForm.receiptAddress[key] = "";
        }
        this.ruleForm.secordReceiptAddress = { ...this.ruleForm.receiptAddress };
        this.ruleForm.isThirdShow = true;
        this.ruleForm.secondDeviceCode = "";
        this.ruleForm.thirdDeviceCode = "";
        this.ruleForm.flyNo = null;
        this.ruleForm.flyTime = null;
        this.ruleForm.trainNum = null;
        this.ruleForm.trainTime = null;
        this.ruleForm.trainForm = null;
        this.ruleForm.trainTo = null;
        this.boxLoading = false
      }
    },
    handleCancel () {
      this.$emit("cancel");
    },
    handleSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.timer = setTimeout(() => {
            setTimeout(() => {
              let params = { ...this.value, ...this.ruleForm };
              this.handleTrack(params)
              this.loading = false;
            }, 400);
          }, 1500);
        } else {
          return false;
        }
      });
    },
    handleTrack (params) {
      if (!params.deviceCode) {
        return this.$message.error(`${params.trackType === 1 ? '请选择电子回单！' : '请输入快递单号！'}`)
      }
      if (['waybill'].includes(this.transportType)) {
        // if ([1, 2].includes(params.checkValue) && !params.deleteFlag) {
        //   if (
        //     params.thirdDeviceCode ||
        //     params.receiptAddress.wayCityCode ||
        //     params.receiptAddress.wayAddress
        //   ) {
        //     if (!params.thirdDeviceCode)
        //       return this.$message.warning("请选择电子回单！");
        //     if (!params.receiptAddress.wayCityCode)
        //       return this.$message.warning("请选择途径地区！");
        //     if (!params.receiptAddress.wayAddress)
        //       return this.$message.warning("请输入详细地址！");
        //   }
        // }
        if (params.checkValue === 3) {
          if (!params.secondDeviceCode) {
            return this.$message.warning("请选择电子回单！");
          } else if (!params.secordReceiptAddress.wayCityCode) {
            return this.$message.warning("请选择途径地区！");
          } else if (!params.secordReceiptAddress.wayAddress) {
            return this.$message.warning("请输入详细地址！");
          }

          if (params.isThirdShow) {
            if (!params.thirdDeviceCode) {
              return this.$message.warning("请选择电子回单！");
            } else if (!params.receiptAddress.wayCityCode) {
              return this.$message.warning("请选择途径地区！");
            } else if (!params.receiptAddress.wayAddress) {
              return this.$message.warning("请输入详细地址！");
            }
          }
        }
      }

      let obj = {};
      obj.orderId = params.orderId;
      obj.trackType = params.trackType;
      obj.deviceCode =
        params.trackType === 1
          ? params.deviceCode
            ? `35160808${params.deviceCode}`
            : null
          : params.deviceCode;
      let arr = [];
      if (params.checkValue === 1 && params.flyNo) {
        arr.push({
          data: {
            orderId: params.orderId,
            sequence: "1",
            transportType: 1,
            startPlace: params.currentAddress[0].stationName,
            endPlace: params.currentAddress[1].stationName,
            transitNo: params.flyNo,
            startTime: this.$moment(params.flyTime).format(
              "YYYY-MM-DD HH:mm:ss"
            )
          },
        });
        // if (params.receiptAddress.wayDistrictCode) {
        arr.push({
          data: {
            orderId: params.orderId,
            ...params.receiptAddress,
            sequence: "2",
            transportType: 4,
            deviceCode: params.thirdDeviceCode ? `35160808${params.thirdDeviceCode}` : obj.deviceCode
          },
        });
        // }
      } else if (params.checkValue === 2 && params.trainNum) {
        arr.push({
          data: {
            orderId: params.orderId,
            sequence: "1",
            transportType: 2,
            startPlace: params.trainForm,
            endPlace: params.trainTo,
            transitNo: params.trainNum,
            startTime: this.$moment(params.trainTime).format(
              "YYYY-MM-DD HH:mm:ss"
            )
          }
        });
        // if (params.receiptAddress.wayDistrictCode) {
        arr.push({
          data: {
            orderId: params.orderId,
            ...params.receiptAddress,
            sequence: "2",
            transportType: 4,
            deviceCode: params.thirdDeviceCode ? `35160808${params.thirdDeviceCode}` : obj.deviceCode
          },
        });
        // }
      } else if (params.checkValue === 3) {
        arr.push({
          data: {
            orderId: params.orderId,
            ...params.secordReceiptAddress,
            sequence: "1",
            transportType: 4,
            deviceCode: `35160808${params.secondDeviceCode}`,
          },
        });
        if (params.isThirdShow) {
          arr.push({
            data: {
              orderId: params.orderId,
              ...params.receiptAddress,
              sequence: "2",
              transportType: 4,
              deviceCode: `35160808${params.thirdDeviceCode}`,
            },
          });
        }
      }
      obj.transports = arr;
      if (this.transportType === "waybill") {
        let dataArr =
          obj.transports.length > 0 &&
          obj.transports.map((item) => {
            return item.data;
          });
        this.actionDispatch({
          waybillId: params.waybillId,
          deviceDTO: { ...obj, transports: dataArr || [] }
        });
      } else if (this.transportType === "onebill") {
        let dataArr =
          obj.transports.length > 0 &&
          obj.transports.map((item) => {
            return item.data;
          });
        this.actionDispatch({
          combineId: params.combineId,
          deviceDTO: { ...obj, transports: dataArr || [] }
        });
      } else if (this.transportType === "batchWaybill") {
        let params = this.orderIds.length ? { orderIds: this.orderIds, ...obj, } : { waybillIds: this.waybillIds, deviceDTO: { ...obj } }
        this.actionDispatch(params);
      } else {
        this.actionDispatch(obj);
      }
    },
    async actionDispatch (params) {
      await axios.post(this.query.url, params)
      this.$message.success('操作成功')
      this.$emit("confirm");
    }
  }
}
</script>
<style scoped>
.form-style {
  min-height: 100px;
}
.footer-button {
  display: flex;
  justify-content: flex-end;
}
</style>